<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form
            size="small"
            :model="pageData"
            layout="inline"
            v-if="permissionStore.hasPermisson('xbjlb.cx')"
          >
            <a-form-item label="处理方式">
              <a-select
                popup-container="html"
                class="bacClass"
                placeholder=""
                :style="{ width: '200px' }"
                v-model="pageData.resultCode"
              >
                <a-option :value="3">全部</a-option>
                <a-option :value="0">本厂维修</a-option>
                <a-option :value="1">委外维修</a-option>
                <a-option :value="2">入次布仓</a-option>
              </a-select>
              <!-- <a-input class="bacClass" placeholder="" v-model="pageData.resultCode" @press-enter="huiche"/>  -->
            </a-form-item>
          </a-form>
        </div>
        <div>
          <Toolbar
            :items="pageData.btnList"
            @select="selectHandler"
            @dyBoufei="handleClick"
            @complete="complete"
            @export="exports"
          >
          </Toolbar>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <div style="text-align: right"></div>
      </div>
    </template>
    <template #pageTabel>
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys
          :rowHeight="33"
          :headerHeight="33"
          :suppressCopyRowsToClipboard="true"
          :suppressDragLeaveHidesColumns="true"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
          :localeText="localeText1"
          v-loading="pageData.pageLoading"
          @columnVisible="onColumnVisible"
          @columnResized="onColumnResized"
          @columnMoved="onColumnMoved"
        ></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :total="pagination.total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
      :page-size="pagination.pageSize"
      :current="pagination.page"
      :page-size-options="pagingList1"
    />

    <a-modal
      :draggable="true"
      v-model:visible="visible"
      @cancel="handleCancel"
      :ok-loading="pageData.loadingPop"
      :width="1000"
      @open="openPop"
    >
      <template #title>
        <span style="font-size: 20px; font-weight: 600"> 修补单</span>
      </template>
      <div id="repaired">
        <div>
          <table id="repairTable" style="border-collapse: collapse">
            <thead>
              <tr class="centerth">
                <th>计划单号</th>
                <th>坯布编号</th>
                <th>坯布名称</th>
                <th>机台号</th>
                <th>条码</th>
                <th>匹号</th>
                <th>疵点</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in pageData.repairList" :key="index">
                <td class="w100-center">{{ item['planOrderCode'] }}</td>
                <td class="w100-center">{{ item['greigeCode'] }}</td>
                <td class="w100-center">{{ item['greigeName'] }}</td>
                <td class="w100-center">{{ item['machineOdd'] }}</td>
                <td class="w100-center">{{ item['barCode'] }}</td>
                <td class="w100-center">{{ item['number'] }}</td>
                <td class="w100-center">{{ item['defectNames'] }}</td>
              </tr>
              <tr>
                <td>总匹数：{{ printData.number }}</td>
                <td colspan="6">备注：{{ printData.remark }}</td>
              </tr>
            </tbody>
          </table>
          <div class="fon-w600">修补人员: {{ printData.repairUser }}</div>
          <div style="width: 100%" class="fon-w600">
            <span style="margin-right: 50px">开始时间：{{ rTime(printData.startDate) }}</span>
            <span style="margin-right: 50px">结束时间：{{ rTime(printData.endDate) }}</span>
            <span>打印日期：{{ pageData.dateNow }}</span>
          </div>
        </div>
      </div>
      <template #footer>
        <a-button type="primary" size="small" @click="printHtml" :disabled="!pageData.isPrint">
          打印
        </a-button>
      </template>
    </a-modal>
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="取消"
      :drawer-style="{ border: '1px solid #ccc' }"
      popup-container=".arco-tabs-content"
      height="89vh"
      placement="bottom"
      :visible="drawer"
      unmountOnClose
      @cancel="drawer = false"
    >
      <template #footer>
        <a-button @click="drawer = false">取消</a-button>
        <a-button @click="save" v-if="pageData.type != 'details'" type="primary">保存</a-button>
      </template>
      <template #title> {{ pageData.type == 'details' ? '查看详情' : '修改' }}修补单</template>
      <el-form
        v-loading="loadingElplus"
        ref="ruleFormRef"
        :model="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
        size="default"
      >
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="公司" prop="outSouringCompany">
              <div style="display: flex">
                <el-input style="width: 200px" v-model="ruleForm.outSouringCompany" disabled />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="修补人员" prop="repairUser">
              <div style="display: flex">
                <el-select
                  v-model="ruleForm.repairUser"
                  multiple
                  clearable
                  popper-class="repairman-options"
                  suffix-icon="none"
                  :suffix-transition="false"
                  style="width: 200px"
                  @remove-tag="handleRemoveTag"
                  :disabled="pageData.type == 'details'"
                />
                <!-- <el-input v-model="ruleForm.repairUser" @input="repaInput" :disabled="pageData.type == 'details'"/> -->

                <el-button
                  type="primary"
                  style="margin-left: 2px"
                  @click="clickRepairman"
                  v-if="pageData.type !== 'details'"
                  >选择
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始时间" prop="startDate ">
              <el-date-picker
                v-model="ruleForm.startDate"
                type="datetime"
                placeholder="请选择开始时间"
                format="YYYY/MM/DD HH:mm"
                :disabled="pageData.type == 'details'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker
                v-model="ruleForm.endDate"
                type="datetime"
                placeholder="请选择结束时间"
                format="YYYY/MM/DD HH:mm"
                :disabled="pageData.type == 'details' || !ruleForm.startDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="金额" prop="amount">
              <el-input v-model="ruleForm.amount" :disabled="pageData.type == 'details'" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="ruleForm.remark"
                :rows="1"
                :disabled="pageData.type == 'details'"
                type="textarea"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-table
          :data="tableData"
          border
          :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ 'text-align': 'center' }"
          style="width: 100%"
        >
          <el-table-column label="检验单号" prop="checkoutOdd" />
          <el-table-column label="计划单号" prop="planOrderCode" width="160" />
          <el-table-column label="坯布编号" prop="greigeCode" width="160" />
          <el-table-column label="坯布名称" prop="greigeName" width="300" />
          <el-table-column label="机台号" prop="machineOdd" width="80" />
          <el-table-column label="匹号" prop="loneOdd" width="80" />
          <el-table-column label="问题点" prop="defectNames" />
          <el-table-column label="检验日期" prop="checkoutDate" width="180" />
        </el-table>
      </el-form>
    </a-drawer>
    <a-modal
      v-model:visible="repairman"
      title="选择修补人员"
      @cancel="repairman = false"
      :draggable="true"
      style="z-index: 1000"
    >
      <a-form :model="ruleForm" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }">
        <!-- <CorporateSectorCascader
          ref="cascaderRef"
          :configCascader="configCascader"
          @changeCascader="changeCascader"
        /> -->
        <a-form-item field="firm" label="公司">
          <el-input v-model="ruleForm.firm" disabled />
        </a-form-item>
        <a-form-item field="department" label="部门">
          <el-input v-model="ruleForm.department" disabled />
        </a-form-item>
        <a-form-item field="repairUser" label="修补人员">
          <el-select-v2
            v-model="repairUser1"
            :options="repairmanList"
            placeholder="选择修补人员"
            filterable
            remote
            :loading="repairmanLoading"
            clearable
            @click="repairmanFocus"
            :remote-method="repairSearch"
            @change="changeRepairMan"
            @clear="clearRepairMan"
            style="width: 400px"
          />
          <!-- <el-select-v2
            v-model="repairUser1"
            :options="repairmanList"
            placeholder="选择修补人员"
            filterable
            :loading="repairmanLoading"
            clearable
            @focus="repairmanFocus"
            style="width: 400px"
          /> -->
          <!-- <el-select
            style="width: 400px"
            @focus="repairmanFocus"
            v-model="ruleForm.repairUser"
            filterable
            placeholder="选择员工"
            :loading="repairmanLoading"
          >
            <el-option
              v-for="item in repairmanList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select> -->
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button type="primary" size="small" @click="saveRepairman">保存</a-button>
      </template>
    </a-modal>
  </pageTabelLayout>
</template>

<script lang="ts">
  import { post, get } from '@/api/http'
  import {
    useTable,
    useRowKey,
    useTableColumn,
    usePagination,
    useRowSelection,
  } from '@/hooks/table'

  import { ref, reactive, onMounted, nextTick } from 'vue'
  import Toolbar from '@/components/Toolbar.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { FormInstance } from '@arco-design/web-vue/es/form'
  import emitter from '@/hooks/useEventBus'
  import validate from '@/hooks/useValidate'
  import dayjs from 'dayjs'
  import printJS from 'print-js'
  import usePermission from '@/store/modules/permission'
  import PageTabelLayout from '@/components/pageTabelLayout.vue'
  // 引入
  import { EXELTABLE } from '@/utils/exportEXCEL'
  
  import { localeText } from '@/api/aggridZw'
  import { pagingList } from '@/api/paging'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
  import { saveOrUpdateGridState as saveOrUpdateGridState01 } from '@/hooks/useGridState'

  interface DefectName {
    checkoutOdd: string | undefined
    repairOdd: string | undefined
    weaveOdd: string | undefined
    machineOdd: string | undefined
    number: string | undefined
    disposeState: number | undefined
    barCode: string | undefined
    checkoutPeople: string | undefined
    problem: string | undefined
    resultCode: number | undefined
    checkoutDate: string | undefined
    disposeDate: string | undefined
    remark: string | undefined
    id: any
  }

  export default {
    name: 'RepairedFactory',
    setup() {
      //查询
      const scrollbar = ref(true)

      function PageSize(val: any) {
        pagination.page = val
        doRefresh()
      }

      function change1(val: any) {
        pagination.pageSize = val
        doRefresh()
      }

      function doRefresh() {
        pageData.pageLoading = true
        updateGridState01()
        post({
          url: 'qms/repairOrder/getPage',
          data: {
            page: pagination.page,
            size: pagination.pageSize,
            repairOdd: '', //修补单号
            repairUser: '', //修补人
            completeState: '', //完成状态  0 未完成 1 已完成
            resultCode: pageData.resultCode == 3 ? undefined : pageData.resultCode, //处理方式
          },
        })
          .then(({ data, code }: any) => {
            if (code === 200) {
              table.handleSuccess(data.list)
              // 查询方法改
              gridOption.value.setRowData(data.list)
              pagination.setTotalSize(data.total)
              pageData.allDataList = data.list
            }
          })
          .catch(console.log)
          .finally(() => {
            pageData.pageLoading = false
          })
      }

      const { selectedRowKeys } = useRowSelection()
      const pagination = usePagination(doRefresh)
      const table = useTable()
      const rowKey = useRowKey('id')
      //检验表单是否含有中文的方法
      const hasChiese = validate.includeChinese
      const tablediv = ref(null)
      const pageData = reactive<{
        DefectName: DefectName[]
        showAdd: boolean
        sideTitle: string
        dropDownData: any
        pageLoading: boolean
        height: number
        tablediv: any
        DefectNameList: []
        resultCode: number | undefined
        checkoutDate: any
        disposeDate: any
        printNum: number | undefined
        detailsList: {}
        repairList: any[]
        allDataList: []
        dateNow: any
        loadingPop: boolean
        btnList: any[]
        isEdit: boolean
        isInfo: boolean
        isPrint: boolean
        type: string
      }>({
        DefectName: [],
        showAdd: false,
        sideTitle: '新增异常处理记录表',
        dropDownData: '',
        pageLoading: false,
        height: 0,
        tablediv: null,
        DefectNameList: [],
        resultCode: 2,
        checkoutDate: '',
        disposeDate: '',
        printNum: 0,
        detailsList: {},
        repairList: [],
        allDataList: [],
        dateNow: '',
        loadingPop: false,
        btnList: [],
        isEdit: false,
        isInfo: false,
        isPrint: false,
        type: '',
      })

      onMounted(() => {
        emitter.on('refresh-RepairedFactory', () => {})
        doRefresh()
      })

      //查询
      const selectHandler = () => {
        pagination.page = 1
        doRefresh()
      }
      const queryData = reactive({
        clothType: '',
      })
      //创建修补单抽屉
      let drawer = ref<boolean>(false)
      const initialState = () => ({
        repairUser: [],
        repairUser1: '',
        repairUserId: [],
        startDate: '',
        endDate: '',
        amount: '',
        remark: '',
        scannedGreyClothIds: [],
        outSouringCompanyId: null,
        outSouringCompany: '',
      })
      let tableData = ref([])
      let ruleForm: any = ref(initialState())
      let loadingElplus = ref<boolean>(false)
      let repairmanList = ref<any>([])
      // 表单ref
      const ruleFormRef = ref<FormInstance>()
      const editHandler = async (row: DefectName, type: string) => {
        pageData.type = type
        try {
          pageData.pageLoading = true
          let res: any = await get({ url: `qms/repairOrder/getInfoById/${row.id}` })
          if (res.code == 200) {
            const { order, orderInfo } = res.data
            drawer.value = true
            nextTick(() => {
              ruleForm.value = order
              repairmanObj[order.repairUser] = order.repairUserId
              ruleForm.value.repairUser = order.repairUser.split(',')
              ruleForm.value.repairUserId = order.repairUserId.split(',')
              tableData.value = orderInfo
            })
            pageData.pageLoading = false
            return
          }
          Message.error(res.message)
        } finally {
          pageData.pageLoading = false
        }
      }
      let rTime = (date: string) => {
        var json_date = new Date(date).toJSON()
        return new Date(new Date(json_date) + 8 * 3600 * 1000)
          .toISOString()
          .replace(/T/g, ' ')
          .replace(/\.[\d]{3}Z/, '')
      }
      //打开员工弹窗
      const clickRepairman = () => {
        CascaderData.company_id = ruleForm.value.outSouringCompanyId
        repairman.value = true
        nextTick(() => {
          repairUser1.value = ''
          repairmanList.value = []
          // cascaderRef.value.resetForm()
        })
      }
      //打印预览PDF
      const printPdf = (e: any) => {
        post({
          url: 'qms/perchingAnomaly/printPerchingAnomaly',
          data: e,
          responseType: 'blob',
        }).then((res: any) => {
          let reader = new FileReader()
          reader.readAsDataURL(res)
          reader.onload = function () {
            let pdfBase64 = reader.result.replace('data:application/pdf;base64,', '')
            printJS({ printable: pdfBase64, type: 'pdf', base64: true })
          }
        })
      }
      const handleRemoveTag = (removed: any) => {
        ruleForm.value.repairUserId = ruleForm.value.repairUserId.filter(
          (item: any) => item !== repairmanObj[removed]
        )
      }
      const repairmanObj = {}
      //保存修补员按钮
      const saveRepairman = () => {
        let label = repairmanList.value.filter((item: any) => {
          return item.id == repairUser1.value
        })
        if (ruleForm.value.repairUser.indexOf(label[0].name) == -1) {
          ruleForm.value.repairUser.push(label[0].name)
          ruleForm.value.repairUserId.push(label[0].id.toString())
          repairmanObj[label[0].name] = label[0].id
          console.log('ruleForm.value.id', ruleForm.value.repairUserId)
        }
        repairman.value = false
        ruleForm.value.firm = ''
        ruleForm.value.department = ''
      }

      const formRef = ref<FormInstance>()
      const visible = ref(false)
      const handleClick = () => {
        let selsetionList = gridOption.value.getSelectedRows()
        if (selsetionList.length <= 0) {
          Message.warning('请勾选需要打印的单据！')
          return
        }
        printPdf(
          gridOption.value.getSelectedRows().map((o: any) => {
            return o['id']
          })
        )
        // visible.value = true
      }
      const handleBeforeOk = (done: any) => {
        pageData.loadingPop = false
        // done()
      }
      const handleCancel = () => {
        visible.value = false
      }
      //打印需要的数据
      let printData = ref({
        startDate: '',
        endDate: '',
        repairUser: '',
        repairUserId: '',
        amount: '',
        remark: '',
        number: '',
      })
      //打开弹窗
      const openPop = async () => {
        let selsetionList = gridOption.value.getSelectedRows()
        if (selsetionList.length == 0) {
          Message.warning('请选择您的单据')
          return
        }
        var date = new Date() // 获取时间
        var year = date.getFullYear() // 获取年
        var month = date.getMonth() + 1 // 获取月
        var strDate = date.getDate() // 获取日
        pageData.dateNow = year + '年' + month + '月' + strDate + '日'
        try {
          let res: any = await get({ url: `qms/repairOrder/getInfoById/${selsetionList[0].id}` })
          if (res.code == 200) {
            const { orderInfo, order } = res.data
            pageData.repairList = orderInfo
            printData.value = order
            pageData.pageLoading = false
            return
          }
        } finally {
        }
      }
      const visible1 = ref(false)

      const handleClick1 = (val: any) => {
        visible1.value = true
        pageData.detailsList = val
      }
      const handleBeforeOk1 = (done: any) => {
        done()
      }
      const handleCancel1 = () => {
        visible1.value = false
      }

      //打印
      function printHtml() {
        printJS({
          printable: 'repaired',
          type: 'html',
          targetStyles: ['*'],
        })
      }

      const headerShow = ref<boolean>(true)

      //设置权限
      // ['查询', '新增', '删除', '导出', '导入']
      const permissionStore = usePermission()
      if (permissionStore.hasPermisson('xbjlb.wc')) {
        pageData.btnList.push('完成')
      }
      if (permissionStore.hasPermisson('xbjlb.cx')) {
        pageData.btnList.push('查询')
      }
      // if (permissionStore.hasPermisson('xbjlb.bc')) {
      //   pageData.btnList.push('保存')
      // }
      if (permissionStore.hasPermisson('xbjlb.dy')) {
        pageData.isPrint = true
        pageData.btnList.push('打印')
      }

      if (permissionStore.hasPermisson('xbjlb.dc')) {
        pageData.btnList.push('导出')
      }
      if (permissionStore.hasPermisson('xbjlb.xg')) {
        pageData.isEdit = true
      }
      if (permissionStore.hasPermisson('xbjlb.xq')) {
        pageData.isInfo = true
      }
      console.log(pageData.isInfo)
      const complete = async () => {
        let selsetionList = gridOption.value.getSelectedRows()
        if (selsetionList.length == 0) {
          Message.warning('请选择您的单据')
          return
        }

        interface lx {
          completeState: string | number
        }

        let condition = selsetionList.every(
          (item: lx) =>
            item.completeState == 0 && item.completeState === selsetionList[0].completeState
        )
        if (!condition) {
          Message.warning('请选择处理状态为未完成的单据')
          return
        }
        let ClothIds = selsetionList.reduce((pre: any, cur: any) => {
          return pre.concat(Number(cur.id))
        }, [])
        ElMessageBox.confirm('请确认修补单已完成', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'success',
        })
          .then(async () => {
            try {
              pageData.pageLoading = true
              let res: any = await post({
                url: 'qms/repairOrder/updateCompleteStateById',
                data: ClothIds,
              })
              if (res.code == 200) {
                ElMessage({
                  type: 'success',
                  message: '操作成功',
                })
                doRefresh()
                drawer.value = false
                pageData.pageLoading = false
                return
              }
              Message.error(res.message)
            } finally {
              pageData.pageLoading = false
            }
          })
          .catch(() => {})
      }

      const repairman = ref<boolean>(false)
      let cascaderRef = ref('')
      let configCascader = ref<{}>({
        corporateWidth: '400px', //公司宽度
        sectorWidth: '400px', //部门宽度
        corporateRquired: false, //公司是否必填
        sectorRquired: false, //部门是否必填
        size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
        corporateName: '公司', //公司label
        sectorName: '部门', //部门label
      })
      let repairUser1 = ref('')
      let repairmanLoading = ref<boolean>(false)
      //查询员工接口
      const repairmanFocus = async (e, text: string = '') => {
        try {
          repairmanLoading.value = true
          CascaderData.ygText = text
          let res: any = await post({ url: 'org/hrEmployee/getPage', data: CascaderData })
          if (res.code == 200) {
            res.data.list.map((item: any) => {
              item.value = item.id
              item.label = item.code + '/' + item.name
            })
            repairmanList.value = res.data.list
            repairmanLoading.value = false
            return
          }
          Message.error(res.message)
        } finally {
          repairmanLoading.value = false
        }
      }
      const repairSearch = (val: string) => {
        repairmanFocus('e', val)
      }
      const changeRepairMan = (id: string) => {
        const personData = repairmanList.value.find((item: any) => item.id == id)
        if (personData) {
          ruleForm.firm = personData.companyName
          ruleForm.department = personData.departmentName
        }
      }
      const clearRepairMan = () => {
        ruleForm.firm = ''
        ruleForm.department = ''
      }
      // 需要传递后端的数据
      const CascaderData = reactive({
        company_id: '',
        obsoleteState: 0,
        deleteState: 0,
        page: 1,
        size: 30,
        ygText: '',
      })
      //保存修补单
      let save = async () => {
        if (!ruleForm.value.startDate) {
          Message.warning('开始时间必填!')
          return
        }
        if (!ruleForm.value.endDate) {
          Message.warning('结束时间必填!')
          return
        }
        if (new Date(ruleForm.value.startDate) > new Date(ruleForm.value.endDate)) {
          Message.warning('开始时间请勿大于结束时间!')
          return
        }
        if (pageData.type == 'details') {
          Message.warning('不能保存详情页')
          return
        }
        if (ruleForm.value.endDate) {
          ruleForm.value.endDate = rTime(ruleForm.value.endDate)
        }
        if (ruleForm.value.startDate) {
          ruleForm.value.startDate = rTime(ruleForm.value.startDate)
        }
        const params = JSON.parse(JSON.stringify(ruleForm.value))
        params.repairUser = params.repairUser.join(',')
        params.repairUserId = params.repairUserId.join(',')
        try {
          loadingElplus.value = true
          let res: any = await post({
            url: 'qms/repairOrder/updateById',
            data: params,
          })
          if (res.code == 200) {
            ElMessage({
              type: 'success',
              message: '修改成功',
            })
            doRefresh()
            drawer.value = false
            loadingElplus.value = false
            return
          }
          Message.error(res.message)
        } finally {
          loadingElplus.value = false
        }
      }
      //公司组件选择触发事件
      const changeCascader = (data: any) => {
        const { corporateId, sectorId } = data
        ruleForm.value.repairUser = ''
        repairmanList.value = []
        CascaderData.company_id = corporateId
        CascaderData.department_id = sectorId
      }
      //输入时去掉id
      let repaInput = () => {
        if (ruleForm.value.repairUserId) {
          ruleForm.value.repairUserId = ''
        }
      }
      // 表格准备事件
      const gridOption = ref()
      const colState = ref()
      const gridReady = (params: any) => {
        gridOption.value = params.api
        colState.value = params.columnApi
      }
      const handleChange = (_data: any) => {
        table.handleSuccess(_data)
      }
      const defaultColDef = {
        sortable: true,
        resizable: true,
        filter: true,
        // flex: 1
      }
      const tableColumns = useTableColumn([
        {
          title: '公司',
          key: 'outSouringCompany',
          dataIndex: 'outSouringCompany',
          width: 150,
        },
        {
          title: '修补单号',
          key: 'repairOdd',
          dataIndex: 'repairOdd',
          width: 150,
        },
        {
          title: '开始时间',
          key: 'startDate',
          dataIndex: 'startDate',
        },
        {
          title: '结束时间',
          key: 'endDate',
          dataIndex: 'endDate',
        },
        {
          title: '金额',
          key: 'amount',
          dataIndex: 'amount',
        },
        {
          title: '匹数',
          key: 'number',
          dataIndex: 'number',
        },
        {
          title: '修补人员',
          key: 'repairUser',
          dataIndex: 'repairUser',
        },
        {
          title: '完成状态',
          key: 'completeState',
          dataIndex: 'completeState',
          slotName: 'completeState',
        },

        {
          title: '创建人',
          key: 'createName',
          dataIndex: 'createName',
        },
        {
          title: '创建时间',
          key: 'createTime',
          dataIndex: 'createTime',
        },
        {
          title: '最后修改人',
          key: 'updateName',
          dataIndex: 'updateName',
        },
        {
          title: '最后修改时间',
          key: 'updateTime',
          dataIndex: 'updateTime',
        },
        {
          title: '处理方式',
          key: 'resultCode',
          dataIndex: 'resultCode',
          slotName: 'resultCode',
          fixed: 'right',
        },
        {
          title: '操作',
          key: 'id',
          dataIndex: 'id',
          slotName: 'action',
          width: 150,
          fixed: 'right',
        },
      ])
      const scroll = {
        x: 2000,
        y: 200,
      }
      let tc: any[] = tableColumns.map((o) => {
        let obj = {
          headerName: o.title,
          field: o.key,
          pinned: o['fixed'],
          tooltipField: o.key,
        }
        obj['width'] = 250
        if (o.slotName === 'action') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['lockPosition'] = 'right'
          obj['width'] = 130
          obj['cellRenderer'] = {
            template: `
            <a-space>
              <el-button link v-if="isEdit&&disabled" type="info" :disabled="disabled">修改</el-button>
              <el-button style="color:#165dff;" link v-if="isEdit&&!disabled" @click="a">修改</el-button>
              <el-button style="color:#165dff;" v-if="isInfo" link @click="b">详情</el-button>
            </a-space>`,
            setup(props: any) {
              const isEdit = ref(pageData.isEdit)
              const isInfo = ref(pageData.isInfo)
              const a = () => {
                editHandler(props.params.data, 'modify')
              }
              const b = () => {
                editHandler(props.params.data, 'details')
              }
              return {
                a,
                b,
                isEdit,
                disabled: props.params.data.completeState == 1,
                isInfo,
              }
            },
          }
        }
        if (o.slotName === 'resultCode') {
          obj['resizable'] = false
          obj['sortable'] = false
          obj['width'] = 120
          obj['cellRenderer'] = {
            template: `<a-space> <el-tag type="warning" v-if="params.data.resultCode==0">本厂维修</el-tag>
          <el-tag type="success" v-else-if="params.data.resultCode==1">委外维修</el-tag><el-tag type="info" v-else>入次布仓</el-tag></a-space>
         `,
          }
          obj['filterParams'] = {
            valueFormatter: function (params: any) {
              return params.value == '0'
                ? '本厂维修'
                : params.value == '1'
                ? '委外维修'
                : params.value == '2'
                ? '入次布仓'
                : ''
            },
          }
        }
        if (o.slotName === 'completeState') {
          obj['resizable'] = false
          obj['filter'] = false
          obj['sortable'] = false
          obj['cellRenderer'] = {
            template: `
            <div>{{ val }}</div>`,
            setup(props: any) {
              let val = ref()
              props.params.data.completeState == 1 ? (val.value = '已完成') : (val.value = '未完成')
              return {
                val,
              }
            },
          }
        }
        return obj
      })

      let a = [
        {
          showRowGroup: 'hide_def',
          headerName: '',
          checkboxSelection: true,
          headerCheckboxSelection: true,
          pinned: 'left',
          width: 50,
          resizable: false,
          filter: false,
          sortable: false,
          minWidth: 50,
          maxWidth: 50,
          lockPosition: 'left',
        },
      ]
      tc = a.concat(tc)

      const localeText1: any = ref(localeText)
      const huiche = () => {
        doRefresh()
      }
      const pagingList1: any = ref(pagingList)

      const { saveGridState: saveGridState01, updateGridState: updateGridState01 } =
        saveOrUpdateGridState01('RepairedFactory', gridOption, colState, tc)
      const onColumnMoved = () => {
        saveGridState01()
      }
      const onColumnResized = () => {
        saveGridState01()
      }
      const onColumnVisible = () => {
        saveGridState01()
      }
      const exports = () => {
        post({
          url: '/qms/repairOrder/getExportExcel',
          data: {
            repairOdd: '', //修补单号
            repairUser: '', //修补人
            completeState: '', //完成状态  0 未完成 1 已完成
            resultCode: pageData.resultCode == 2 ? undefined : pageData.resultCode, //处理方式
          },
        }).then(({ data, code }: any) => {
          if (code === 200) {
            EXELTABLE(tc, data, '修补记录表')
          }
        })
      }
      const handleRepairCancel = () => {
        repairman.value = false
        ruleForm.firm = ''
        ruleForm.department = ''
      }
      return {
        handleRemoveTag,
        handleRepairCancel,
        clearRepairMan,
        changeRepairMan,
        repairSearch,
        saveOrUpdateGridState01,
        saveGridState01,
        updateGridState01,
        onColumnMoved,
        onColumnResized,
        onColumnVisible,
        colState,
        pagingList1,
        huiche,
        localeText1,
        tc,
        gridReady,
        headerShow,
        scroll,
        scrollbar,
        tablediv,
        hasChiese,
        formRef,
        selectedRowKeys,
        pagination,
        tableColumns,
        table,
        rowKey,
        pageData,
        queryData,
        editHandler,
        selectHandler,
        dayjs,
        visible,
        handleClick,
        handleBeforeOk,
        handleCancel,
        visible1,
        handleClick1,
        handleBeforeOk1,
        handleCancel1,
        printJS,
        printHtml,
        openPop,
        PageSize,
        change1,
        defaultColDef,
        handleChange,
        drawer,
        ruleFormRef,
        ruleForm,
        loadingElplus,
        tableData,
        repairmanList,
        repaInput,
        CascaderData,
        configCascader,
        cascaderRef,
        save,
        repairUser1,
        repairmanLoading,
        repairmanFocus,
        changeCascader,
        repairman,
        saveRepairman,
        clickRepairman,
        printData,
        rTime,
        complete,
        permissionStore,
        exports,
      }
    },
    components: { Toolbar, PageTabelLayout, CorporateSectorCascader },
  }
</script>
<style scoped lang="less">
  #detailsTable td,
  #repairTable td,
  #detailsTable th,
  #repairTable th {
    border: 1px solid #ccc;
    padding: 10px;
  }

  .fon-w600 {
    font-weight: 600;
    margin-top: 20px;
  }

  .w100-center {
    width: 120px !important;
    text-align: center !important;
  }

  .centerth th {
    width: 120px !important;
    text-align: center !important;
  }
</style>
